package com.fanjia.security01demo.config;

import com.fanjia.security01demo.service.Impl.UserDetailsImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author fanjia
 * @className SecurityConfig
 * @description TODO
 * @date 2021/3/25 20:17
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsImpl myUserDetails;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {

        http.csrf().disable();
        http.formLogin().loginProcessingUrl("/login");
        http.authorizeRequests()
                //定义需要验证的请求
                .antMatchers("/index","/info").authenticated()
                .anyRequest().permitAll()//其余的不需要验证
                .and()
                .logout()
                .permitAll()//定义logout不需要验证

                .and().csrf().disable();//使用form表单登录

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(myUserDetails).passwordEncoder(passwordEncoder());
    }

}
